package com.springbootmybatiscurd.controller;

import com.springbootmybatiscurd.pojo.Result;
import com.springbootmybatiscurd.utils.AliOSSUtils;
import com.springbootmybatiscurd.utils.UploadFile;
import com.springbootmybatiscurd.utils.uuid.getMachineUUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
@CrossOrigin(origins = "*")   //设置跨域
public class controllerUpload {

  /*  @PostMapping("/uploadFrom")
  /*  public Result uploadFrom(String username, Integer age, MultipartFile image) throws IOException {
        log.info("文件上传:{},{},{}",username,age,image);
        //读取原始文件名
        String originalFilename = image.getOriginalFilename();
        // 构造唯一的文件名(不能重复) --uuid(通用唯一识别码)
        String uuid = new getMachineUUID().getUUID();
        // 查到"."这个在字符串的索引
        int index = originalFilename.lastIndexOf(".");
        // 截取字符串.后面的
        String getImageType = originalFilename.substring(index);
        // 组成不重复的图片名称
        String newFileName = uuid + getImageType;
        image.transferTo(new File("D:\\upload\\temp\\"+newFileName));
        return Result.success();

    }*/

    /**
     * 阿里云oss服务器上传
     * */
  /*  @Autowired
    private AliOSSUtils aliOSSUtils;
    @PostMapping("/uploadFrom")
    public Result uploadFrom(MultipartFile image) throws IOException {

        log.info("文件上传的原始地址：{}",image.getOriginalFilename());
        String url = aliOSSUtils.upload(image);
        log.info("阿里云返回的url地址：{}",url);
        return Result.success(url);
    }
*/
    /**
     * 本地服务器上传图片
     * */
   @Autowired
  private   UploadFile uploadFile;
    @PostMapping("/upload")
    public Result handleFileUpload( MultipartFile image) throws IOException {
        if (image.isEmpty()) {
            return Result.success("Upload failed");
        }
        String url = uploadFile.Upload(image);

        return Result.success(url);
    }
}
